package com.njlime.sys.controller;

import com.alibaba.fastjson.JSONObject;
import com.njlime.cms.service.sys.InformationService;
import com.njlime.core.base.controller.BaseController;
import com.njlime.core.exception.ExceptionState;
import com.njlime.core.helper.PageBean;
import com.njlime.core.utils.DateUtil;
import com.njlime.core.utils.StringUtil;
import com.njlime.member.service.sys.MemberService;
import com.njlime.setting.entities.Announce;
import com.njlime.setting.service.AnnounceService;
import com.njlime.sys.entities.Unit;
import com.njlime.sys.entities.User;
import com.njlime.sys.security.FormAuthenticationFilter;
import com.njlime.sys.security.SystemAuthorizingRealm.Principal;
import com.njlime.sys.security.util.UserUtils;
import com.njlime.sys.service.UserService;
import com.njlime.sys.util.NoteSendUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 登录管理
 * Created by Dean on 2017-7-20.
 */
@Controller
@RequestMapping(value = "")
public class LoginController extends BaseController {

    @Resource
    private UserService userService;
    @Resource
    private InformationService informationService;
    @Resource
    private MemberService memberService;
    @Resource
    private AnnounceService announceService;

    /**
     * 登录视图
     *
     * @return
     */
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public ModelAndView loginView(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        Principal principal = UserUtils.getPrincipal();
        // 如果已经登录，则跳转到管理首页
        if (principal != null && !principal.isMobileLogin()) {
            User user = UserUtils.getUser();
            modelAndView.addObject("name", user.getName());
            modelAndView.addObject("head_url", user.getHead_url());
            modelAndView.setViewName("/index");
        } else {
            modelAndView.setViewName("/login");
        }
        return modelAndView;
    }

    /**
     * 登录失败方法
     *
     * @return
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public ModelAndView login(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("/login");
        Principal principal = UserUtils.getPrincipal();
        // 如果已经登录，则跳转到首页
        if (principal != null) {
            User user = UserUtils.getUser();
            modelAndView.addObject("name", user.getName());
            modelAndView.addObject("head_url", user.getHead_url());
            modelAndView.setViewName("/index");
        } else {
            String username = WebUtils.getCleanParam(request, FormAuthenticationFilter.DEFAULT_USERNAME_PARAM);
            String exception = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
            String message = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_MESSAGE_PARAM);
            // 非授权异常，登录失败，次数加一
            if (!UnauthorizedException.class.getName().equals(exception) && username != null) {
                UserUtils.loginFail(username, true, false);
            }
            request.getSession().removeAttribute("validateCode");
            modelAndView.addObject("msg", message);
            if (StringUtils.isBlank(message) || StringUtils.equals(message, "null")) {
                modelAndView.addObject("msg", "登陆失败，请重试");
            }
        }
        return modelAndView;
    }

    /**
     * 微信扫码登录
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "wechatLogin", method = RequestMethod.GET)
    public void wechatLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String code = WebUtils.getCleanParam(request, "code");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        String url = request.getContextPath() + "/login";
        out.println("<form name='paySubmit' method='post' action='" + url + "' >");
        out.println("<input type='hidden' name='code' value='" + code + "'>"); //如有多个，则写多个hidden即可
        out.println("</form>");
        out.println("<script>");
        out.println("document.paySubmit.submit()");
        out.println("</script>");
    }

    /**
     * 登录成功方法
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "index")
    public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView modelAndView = new ModelAndView("/index");
        Principal principal = UserUtils.getPrincipal();
        User user = UserUtils.getUser();
        modelAndView.addObject("name", user.getName());
        modelAndView.addObject("head_url", user.getHead_url());
        UserUtils.loginFail(principal.getLoginName(), false, true);
        return modelAndView;
    }


    /**
     * 首页数据
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/sys/loginChart")
    public String loginChart(HttpServletRequest request) {
        //处理首页数据
        JSONObject result = new JSONObject();
        int orderCount = 0;
        Date end = DateUtil.getDayStart(new Date());
        Date start = DateUtil.addDay(end, -7);
        String[] label = DateUtil.getDateArray(start, end, "yyyy-MM-dd");
        //Unit unit = getLoginUser().getRootUnit();
        Unit unit = getLoginUserUnit();
        Map<String,Object> map = informationService.welcomeReport(unit);
        //List<Map<String,Object>> orderReport = orderService.welcomeReport(unit);
        List<Map<String,Object>> orderReport = new ArrayList<>();
        List<Map<String,Object>> memberReport = memberService.memberReport(unit, start, end);
        String[] numChart = new String[label.length];
        String[] amountChart = new String[label.length];
        String[] subChart = new String[label.length];
        for(int m = 0; m < label.length; m++) {
            if (orderReport != null && orderReport.size() > 0) {
                boolean is_data = false;
                for (Map<String, Object> anOrderReport : orderReport) {
                    Integer num = Integer.parseInt(anOrderReport.get("orderNum").toString());
                    orderCount += num;
                    if (anOrderReport.get("date").toString().equals(label[m])) {
                        is_data = true;
                        numChart[m] = anOrderReport.get("orderNum").toString();
                        amountChart[m] = Integer.valueOf(anOrderReport.get("orderAmount").toString()) / 100.0 + "";
                    }
                }
                if (!is_data){
                    numChart[m] = "0";
                    amountChart[m] = "0";
                }
            }
            if (memberReport != null && memberReport.size() > 0) {
                boolean is_data = false;
                for (Map<String, Object> anMemberReport : memberReport) {
                    if (anMemberReport.get("report_date").toString().equals(label[m])) {
                        is_data = true;
                        subChart[m] = anMemberReport.get("sub_num").toString();
                    }
                }
                if (!is_data){
                    subChart[m] = "0";
                }
            }
        }
        result.put("label",label);
        result.put("numChart",numChart);
        result.put("amountChart",amountChart);
        result.put("subChart",subChart);
        result.put("articleNum",map.get("articleNum"));
        result.put("readNum",map.get("readNum"));
        result.put("orderCount",orderCount);
        Map<String,Object> member = memberService.welcomeReport(unit);
        result.put("memberNum",member.get("memberNum"));

        //帮助公告
        Announce announce = new Announce();
        announce.setType(Announce.AnnounceType.ANNOUNCE);
        List<Map<String,Object>> aList = announceService.list(new PageBean(5), announce).getMapList();
        result.put("aList", aList);
        announce.setType(Announce.AnnounceType.HELP);
        List<Map<String,Object>> hList = announceService.list(new PageBean(3), announce).getMapList();
        result.put("hList", hList);
        return toJsonSuccessData(result);
    }


    /**
     * 权限检测
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/checkPermission")
    public String checkPermission(HttpServletRequest request, String url) {
        try{
            Subject subject = SecurityUtils.getSubject();
            boolean isPermitted = subject.isPermitted(url);
            if(!isPermitted){
                return toJsonErrorData(ExceptionState.PERMISSION_EXCEPTION,"没有此操作的权限");
            }
        }catch (Exception e){
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.PERMISSION_EXCEPTION,"没有此操作的权限");
        }
        return toJsonSuccessData();
    }

    @RequestMapping(value = "exceptionView", method = RequestMethod.GET)
    public ModelAndView exceptionView(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("/exception");
        modelAndView.addObject("resCode", request.getAttribute("resCode"));
        modelAndView.addObject("message", request.getAttribute("message"));
        return modelAndView;
    }

}
